var orderModel = require("../models/order.model");
var flightModel = require("../models/flight.model");
var testFunc= require('./publicFunc/travelTest.js');

goBack = (req, res, next, goData) =>{
    let body = JSON.parse(req.body.data),
        initalValues = body.initalValues; 
    console.log("返程查询id", initalValues.toTrip.id);  
    flightModel.find({_id: initalValues.toTrip.id}, (err, data)=>{
        if(err){
            console.error(err);
            res.json({
                success: false,
                description: "查询返程出错"
            })
        }else{
            data = data[0];
            let classType = "economyClass";
                switch(initalValues.toType){
                    case "1": classType = "businessClass"; break;
                    case "2": classType = "firstClass"; break;
                }
            let residualTicket = data[classType].residualTicket - Number(body.values.number);//预定去程后飞机剩余的机票，不能是负数。

            if(residualTicket >= 0){//返程的票
                console.log("进入返程的更新处理");
                let newUpdata = {};
                switch(initalValues.toType){
                    case "0": newUpdata = { "economyClass": {...data.economyClass, residualTicket: data.economyClass.residualTicket - Number(body.values.number)}}; break;
                    case "1": newUpdata = { "businessClass": {...data.businessClass, residualTicket: data.businessClass.residualTicket - Number(body.values.number)}}; break;
                    case "2": newUpdata = { "firstClass": {...data.firstClass, residualTicket: data.firstClass.residualTicket - Number(body.values.number)}}; break;
                }
                //返程的票数锁定
                flightModel.findByIdAndUpdate(initalValues.toTrip.id, newUpdata, {new: true}, (err, updata)=>{
                    if(err){
                        res.json({
                            success: false,
                            description: "锁定返程出错",
                            data: err
                        })
                        console.error(err);
                    }else{
                        //新增一个订单去程订单
                        let time = new Date().getTime(),
                            orderNumber = time + "" + parseInt(Math.random() * 99 + 10),
                            orderObj = {
                                orderNumber: orderNumber,
                                username: body.username,
                                ticketingTime: time,
                                company: initalValues.toTrip.flight.company,
                                start:initalValues.toTrip.start,
                                end: initalValues.toTrip.end,
                                classType: initalValues.toType,
                                contact: body.values.contact,
                                number: body.values.number,
                                passenger:(()=>{
                                    let arr = [], obj = {}, passenger = body.values.passenger, classInf = initalValues.toTrip[classType];
                                    for(let i = 0; i < passenger.length; i++){
                                        obj = {
                                            orderNumber: orderNumber + i,
                                            name: passenger[i].name,
                                            IDnumber: passenger[i].IDnumber,
                                            type: passenger[i].type,
                                            phone: passenger[i].phone,
                                            price: (()=>{
                                                let price  = 0;
                                                if(passenger[i].type === "0"){//"0":成人，1：儿童，2：婴儿
                                                    price = classInf.afterPrice + classInf.fuel + classInf.construction;
                                                }
                                                if(passenger[i].type === "1"){//儿童票价：航线标准价的50%，不收机建费，燃油费为成人的50%。
                                                    price = (classInf.afterPrice + classInf.fuel) * 0.5;
                                                }
                                                if(passenger[i].type === "2"){//婴儿票按照航线标准价格的10%不收机建及燃油费。(注：婴儿票无座，必须与成人购买同一舱等的机票)
                                                    price = classInf.afterPrice * 0.1;
                                                }
                                                return price;
                                            })(),
                                            unsubscribe:false
                                        };
                                        arr.push(obj);
                                    }
                                    return arr;
                                })(),
                            };
                        let newOrder = new orderModel(orderObj);
                        newOrder.save((err, toData)=>{
                            if(err){
                                console.error(err);
                                res.json({
                                    success: false,
                                    description: "新增去程订单出错~",
                                })
                            }else{
                                res.json({
                                    success: true,
                                    description:"往返的结果",
                                    data:{
                                        goID: initalValues.goTrip.id,//预定去程的航班id
                                        goData: goData,
                                        toID: initalValues.toTrip.id,
                                        toData: toData
                                    }
                                })
                            }
                        })
                    }
                })
            }else{
                res.json({
                    success: false,
                    description: "返程票不够",
                })
            }
        }
    })
}

toTimeout = (req, res, next) =>{
    let body = JSON.parse(req.body.data);
    console.log("取消票的支付body", body);
    flightModel.find({_id: body.toID}, (err, data)=>{
        if(err){
            console.error(err);
            res.json({
                success: false,
                description: "超时取消返程订单查询航程出错"
            })
        }else{
            let newUpdata = {};

            data = data[0];
            console.log("data", data);//预定的item
            switch(body.toData.classType){//预定的舱型
                case 0: newUpdata = { "economyClass": {...data.economyClass, residualTicket: data.economyClass.residualTicket + body.toData.number}}; break;
                case 1: newUpdata = { "businessClass": {...data.businessClass, residualTicket: data.businessClass.residualTicket + body.toData.number}}; break;
                case 2: newUpdata = { "firstClass": {...data.firstClass, residualTicket: data.firstClass.residualTicket + body.toData.number}}; break;
            }
            flightModel.findByIdAndUpdate(body.toID, newUpdata, {new: true}, (err, updata)=>{
                if(err){
                    res.json({
                        success: false,
                        description: "取消返程锁定票数出错",
                        data: err
                    })
                    console.error(err);
                }else{
                    //改变返程订单状态为1
                    orderModel.findByIdAndUpdate(body.toData._id, {state: 1}, {new: true}, (err, updata)=>{
                        if(err){
                            console.error(err);
                            res.json({
                                success:false,
                                description:"处理返程订单状态出错",
                            })
                        }else{
                            //如果还有返程的，再取消返程的。
                            res.json({
                                success:true,
                                description:"返程订单取消锁定成功"
                            })
                        }
                    })
                }
            })//flightModel
        }
    })
}

module.exports={
    travelTest:function(req, res, next){
        let body = JSON.parse(req.body.data);
        testFunc.isConflict(req, res, next, body, (req, res, next, flag) =>{
            if(flag){
                res.json({
                    success: true,
                    description:"没问题",
                    data:{
                        state:0
                    }
                })
            }else{
                res.json({
                    success: true,
                    description:"乘客行程冲突",
                    data:{
                        state:1
                    }
                })
            }
        });
    },
    bookFirst:function(req, res, next){
        //预定第一步，提交信息并且锁定票
        //initalValues是航程的信息，里面goTrip：去程，toTrip返程
        //values是乘客的信息//预定票，如果是婴儿票就没有座位。
        //submiteTime是乘客提交时间
         //单程：往返的前一段
        //往返首先查询去程的锁定了后再看有没有返程的，有返程的再锁定返程的，如果返程的不够就将去程的票退回去。residualTicket是余票字段
        let body = JSON.parse(req.body.data),
            initalValues = body.initalValues;

        flightModel.find({_id: initalValues.goTrip.id}, (err, data)=>{
            if(err){
                console.error(err);
                res.json({
                    success: false,
                    description: "查询去程出错"
                })
            }else{
                data = data[0];
                let classType = "economyClass";
                switch(initalValues.goType){
                    case "1": classType = "businessClass"; break;
                    case "2": classType = "firstClass"; break;
                }
                let residualTicket = data[classType].residualTicket - Number(body.values.number);//预定去程后飞机剩余的机票，不能是负数。

                if(residualTicket >= 0){
                    if(initalValues.toType){//有返程，先新增去程订单。
                        let newUpdata = {};
                        switch(initalValues.goType){
                            case "0": newUpdata = { "economyClass": {...data.economyClass, residualTicket: residualTicket}}; break;
                            case "1": newUpdata = { "businessClass": {...data.businessClass, residualTicket: residualTicket}}; break;
                            case "2": newUpdata = { "firstClass": {...data.firstClass, residualTicket: residualTicket}}; break;
                        }
                        flightModel.findByIdAndUpdate(initalValues.goTrip.id, newUpdata, {new: true}, (err, updata)=>{
                            if(err){
                                res.json({
                                    success: false,
                                    description: "锁定去程出错",
                                    data: err
                                })
                                console.error(err);
                            }else{
                                //新增一个订单去程订单
                                let time = new Date().getTime(),
                                    orderNumber = time + "" + parseInt(Math.random() * 99 + 10),
                                    orderObj = {
                                        orderNumber: orderNumber,
                                        username: body.username,
                                        ticketingTime: time,
                                        company: initalValues.goTrip.flight.company,
                                        start:initalValues.goTrip.start,
                                        end: initalValues.goTrip.end,
                                        classType: initalValues.goType,
                                        contact: body.values.contact,
                                        number: body.values.number,
                                        passenger:(()=>{
                                            let arr = [], obj = {}, passenger = body.values.passenger, classInf = initalValues.goTrip[classType];
                                            for(let i = 0; i < passenger.length; i++){
                                                obj = {
                                                    orderNumber: orderNumber + i,
                                                    name: passenger[i].name,
                                                    IDnumber: passenger[i].IDnumber,
                                                    type: passenger[i].type,
                                                    phone: passenger[i].phone,
                                                    price: (()=>{
                                                        let price  = 0;
                                                        if(passenger[i].type === "0"){//"0":成人，1：儿童，2：婴儿
                                                            price = classInf.afterPrice + classInf.fuel + classInf.construction;
                                                        }
                                                        if(passenger[i].type === "1"){//儿童票价：航线标准价的50%，不收机建费，燃油费为成人的50%。
                                                            price = (classInf.afterPrice + classInf.fuel) * 0.5;
                                                        }
                                                        if(passenger[i].type === "2"){//婴儿票按照航线标准价格的10%不收机建及燃油费。(注：婴儿票无座，必须与成人购买同一舱等的机票)
                                                            price = classInf.afterPrice * 0.1;
                                                        }
                                                        return price;
                                                    })(),
                                                    unsubscribe:false
                                                };
                                                arr.push(obj);
                                            }
                                            return arr;
                                        })(),
                                    };
                                let newOrder = new orderModel(orderObj)
                                newOrder.save((err, goData)=>{
                                    if(err){
                                        console.error(err);
                                        res.json({
                                            success: false,
                                            description: "新增去程订单出错~",
                                        })
                                    }else{
                                        //新增返程订单
                                        goBack(req, res, next, goData);
                                    }
                                })
                            }
                        })
                    }else{
                        //没有返程的，锁定n张票后返回
                        let newUpdata = {};
                        switch(initalValues.goType){
                            case "0": newUpdata = { "economyClass": {...data.economyClass, residualTicket: residualTicket}}; break;
                            case "1": newUpdata = { "businessClass": {...data.businessClass, residualTicket: residualTicket}}; break;
                            case "2": newUpdata = { "firstClass": {...data.firstClass, residualTicket: residualTicket}}; break;
                        }
                        flightModel.findByIdAndUpdate(initalValues.goTrip.id, newUpdata, {new: true}, (err, updata)=>{
                            if(err){
                                res.json({
                                    success: false,
                                    description: "锁定去程出错",
                                    data: err
                                })
                                console.error(err);
                            }else{
                                //新增一个订单去程订单，再返回
                                let time = new Date().getTime(),
                                    orderNumber = time + "" + parseInt(Math.random() * 99 + 10),
                                    orderObj = {
                                        orderNumber: orderNumber,
                                        username: body.username,
                                        ticketingTime: time,
                                        company: initalValues.goTrip.flight.company,
                                        start:initalValues.goTrip.start,
                                        end: initalValues.goTrip.end,
                                        classType: initalValues.goType,
                                        contact: body.values.contact,
                                        number: body.values.number,
                                        passenger:(()=>{
                                            let arr = [], obj = {}, passenger = body.values.passenger, classInf = initalValues.goTrip[classType];
                                            for(let i = 0; i < passenger.length; i++){
                                                obj = {
                                                    orderNumber: orderNumber + i,
                                                    name: passenger[i].name,
                                                    IDnumber: passenger[i].IDnumber,
                                                    type: passenger[i].type,
                                                    phone: passenger[i].phone,
                                                    price: (()=>{
                                                        let price  = 0;
                                                        if(passenger[i].type === "0"){//"0":成人，1：儿童，2：婴儿
                                                            price = classInf.afterPrice + classInf.fuel + classInf.construction;
                                                        }
                                                        if(passenger[i].type === "1"){//儿童票价：航线标准价的50%，不收机建费，燃油费为成人的50%。
                                                            price = (classInf.afterPrice + classInf.fuel) * 0.5;
                                                        }
                                                        if(passenger[i].type === "2"){//婴儿票按照航线标准价格的10%不收机建及燃油费。(注：婴儿票无座，必须与成人购买同一舱等的机票)
                                                            price = classInf.afterPrice * 0.1;
                                                        }
                                                        return price;
                                                    })(),
                                                    unsubscribe:false
                                                };
                                                arr.push(obj);
                                            }
                                            return arr;
                                        })(),
                                    };
                                let newOrder = new orderModel(orderObj)
                                newOrder.save((err, goData)=>{
                                    if(err){
                                        console.error(err);
                                        res.json({
                                            success: false,
                                            description: "新增去程订单出错~",
                                        })
                                    }else{
                                        res.json({
                                            success: true,
                                            description: "只有单程的~",
                                            data:{
                                                goID: initalValues.goTrip.id,//预定去程的航班id
                                                goData: goData,
                                            }
                                        })
                                    }
                                })
                            }
                        })
                    }
                }else{
                    res.json({
                        success: false,
                        description: "去程票不够",
                    })
                }
            }
        })
    },
    bookTimeout:function(req, res, next){
        //超时取消订单的锁定,使用订单的id,//body.data._id更新fightID的票数量，body.id-》order的状态改变。
        let body = JSON.parse(req.body.data);
        
        flightModel.find({_id: body.goID}, (err, data)=>{
            if(err){
                console.error(err);
                res.json({
                    success: false,
                    description: "超时取消订单查询航程出错"
                })
            }else{
                let newUpdata = {};

                data = data[0];
                switch(body.goData.classType){//预定的舱型
                    case 0: newUpdata = { "economyClass": {...data.economyClass, residualTicket: data.economyClass.residualTicket + body.goData.number}}; break;
                    case 1: newUpdata = { "businessClass": {...data.businessClass, residualTicket: data.businessClass.residualTicket + body.goData.number}}; break;
                    case 2: newUpdata = { "firstClass": {...data.firstClass, residualTicket: data.firstClass.residualTicket + body.goData.number}}; break;
                }
                flightModel.findByIdAndUpdate(body.goID, newUpdata, {new: true}, (err, updata)=>{
                    if(err){
                        res.json({
                            success: false,
                            description: "取消锁定票数出错",
                            data: err
                        })
                        console.error(err);
                    }else{
                        //改变去程订单状态为1
                        orderModel.findByIdAndUpdate(body.goData._id, {state: 1}, {new: true}, (err, updata)=>{
                            if(err){
                                console.error(err);
                                res.json({
                                    success:false,
                                    description:"处理订单状态出错",
                                })
                            }else{
                                //如果还有返程的，再取消返程的。
                                if(body.toID){
                                    toTimeout(req, res, next);
                                }else{
                                    res.json({
                                        success:true,
                                        description:"去程订单取消锁定成功"
                                    })
                                }
                            }
                        })
                    }
                })//flightModel
            }
        });
    },
    bookPay: function(req, res, next){
        //goID, toID
        let body = JSON.parse(req.body.data);
        //先改变去程的
        console.log("支付的body", body);
        orderModel.findById(body.goID, (err, doc)=>{
            if(err){
                res.json({
                    success: false,
                    description:　"完成去程更新查询出错"
                })
            }else{
                doc.state = 2;
                orderModel.findByIdAndUpdate(body.goID, doc, {new: true}, (err, data)=>{
                    if(err){
                        console.error(err);
                        res.json({
                            success: false,
                            description:　"完成去程更新出错"
                        })
                    }else{ 
                        if(body.toID){//这个好像还有问题
                            orderModel.findById(body.toID,(err, doc)=>{
                                if(err){
                                    console.error(err);
                                    res.json({
                                        success: false,
                                        description:"完成返程更新查询出错"
                                    })
                                }else{
                                    doc.state = 2;
                                    console.log("更新fa返回状态为支付的", doc);
                                    orderModel.findByIdAndUpdate(body.toID, doc, {new: true}, (err, todata)=>{
                                        if(err){
                                            console.error(err);
                                            res.json({
                                                success: false,
                                                description:"完成返程更新出错"
                                            })
                                        }else{
                                            res.json({
                                                success:true,
                                                description:'完成订单',
                                                data: todata
                                            })
                                        }
                                    })
                                }
                            })// orderModel.findById(body.goID
                        }else{
                            res.json({
                                success: true,
                                description:"完成订单",
                                data: data
                            })
                        }
                    }
                })//orderModel.findByIdAndUpdate(body.goID,
            }
        });
    },
    cancelOrder:function(req, res, next){//未出行取消订单&退票
        let body = JSON.parse(req.body.data);
        //先将票flightID:,classType:退回去，再改变订单orderID:的状态
        // {
        //     username: this.state.data.goData.username,
        //     orderID: this.state.data.goData._id,
        //     flightID: this.state.initalValues.goTrip.id,
        //     classType:this.state.initalValues.goType,
        //     select: this.state.unsubVal.goSelect,
        //     number: this.state.data.goData.number
        // }
        flightModel.findById(body.flightID, (err, data)=>{
            if(err){
                console.error(err);
                res.json({
                    success: false,
                    description:"取消订单查询出错"
                })
            }else{
                //出行时间超过了不能取消订单。
                let updata = {};
                console.log("退订的data", data);
                switch(body.classType){
                    case '0': updata = {
                        economyClass:{
                            ...data.economyClass,
                            residualTicket: data.economyClass.residualTicket + body.select.length
                        }
                    }; break;
                    case '1': updata = {
                        businessClass:{
                            ...data.businessClass,
                            residualTicket: data.businessClass.residualTicket + body.select.length
                        }
                    }; break;
                    case '2': updata = {
                        firstClass:{
                            ...data.firstClass,
                            residualTicket: data.firstClass.residualTicket + body.select.length
                        }
                    }; break;
                }
                flightModel.findByIdAndUpdate(data._id, updata, {new: true},(err, upeddata)=>{
                    if(err){
                        console.error(err);
                        res.json({
                            success: true,
                            description:"更新航班票出错",
                        })
                    }else{
                        //更新订单信息，将订单要退订的那几个人变成已经退订，3：部分乘客退订还有没退订的,4：全部已取消&&退订,
                        let state = {state: 4}
                        if(body.number > body.select.length){
                            state.state = 3;
                        }
                        orderModel.findByIdAndUpdate(body.orderID, state, {new: true}, (err, data)=>{
                            if(err){
                                console.error(err);
                                res.json({
                                    success: false,
                                    description:"在订单状态更新出错"
                                })
                            }else{
                                res.json({
                                    success: true,
                                    description: "退订成功",
                                    data: data
                                })
                            }
                        })
                    }
                })
            }
        })
    },
    deleteOrder:function(req, res, next){//删除订单
        console.log("删除订单");
    }
}